const app = getApp();
const utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagePath: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var cardinfo = JSON.parse(this.decodeUnicode((options.cardinfo)));
    this.getAvaterInfo(cardinfo)
  },

  // 解码
  decodeUnicode:function (str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
  },

  //下载头像
  getAvaterInfo: function (cardInfo) {
    wx.showLoading({ title: '生成中...',mask: true,});
    var that = this;
    if (cardInfo.CardInfo.Avater) {
      wx.downloadFile({
        url: cardInfo.CardInfo.Avater,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var avaterSrc = res.tempFilePath;
            that.getQrCode(avaterSrc, cardInfo);
          }else{
            wx.showToast({
              title: '头像下载失败！',
              icon:'none',
              duration: 2000,
              success:function(){
                var avaterSrc = "";
                that.getQrCode(avaterSrc, cardInfo);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var avaterSrc = "";
      that.getQrCode(avaterSrc, cardInfo);
    }
  },

  //下载二维码
  getQrCode: function (avaterSrc, cardInfo) {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    if (cardInfo.CardInfo.QrCode) {
      wx.downloadFile({
        url: cardInfo.CardInfo.QrCode,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePosteCanvas(cardInfo, avaterSrc, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePosteCanvas(cardInfo, avaterSrc, codeSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var codeSrc = "";
      that.sharePosteCanvas(cardInfo, avaterSrc, codeSrc);
    }
  },

  //canvas绘制分享海报
  sharePosteCanvas: function (cardInfo, avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas');
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width * 0.8;
      var left = rect.left + 5;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, left, 20, width, width);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }
    
      if (cardInfo.TagList){
        if (cardInfo.TagList.length > 0) {
          ctx.fillText(cardInfo.TagList[0].TagName, left + 20, width - 4); //标签
          const metrics = ctx.measureText(cardInfo.TagList[0].TagName); //测量文本信息
          ctx.stroke();
          ctx.rect(left + 10, width - 20, metrics.width + 20, 25);
          ctx.setFillStyle('rgba(255,255,255,0.4)');
          ctx.fill();
        }
      }

      if (cardInfo.CardInfo.Name) {
        ctx.setFontSize(14);
        ctx.setFillStyle('#000');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.CardInfo.Name, left, width + 60); //姓名
      }

      if (cardInfo.CardInfo.Position) {
        ctx.setFontSize(12);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.CardInfo.Position, left, width + 85); //职位
      }

      if (cardInfo.CardInfo.Mobile) {
        ctx.setFontSize(12);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.CardInfo.Mobile, left, width + 105); //电话
      }

      if (cardInfo.CardInfo.Company) {
        // 公司名称
        const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength(cardInfo.CardInfo.Company, CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#000');
        ctx.setFontSize(10);
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], left, width + 150 + contentHh * m);
        }
      }

      //  绘制二维码cardInfo.CardInfo.QrCode
      if (codeSrc) {
        ctx.drawImage(codeSrc, left + 160, width + 40, width / 3, width / 3)
        ctx.setFontSize(10);
        ctx.setFillStyle('#000');
        ctx.fillText("微信扫码或长按识别", left + 160, width + 150);
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              utils.aiCardActionRecord(19);
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})